package com.hsy.swu.utils

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.provider.Settings
import android.telephony.TelephonyManager
import androidx.core.content.ContextCompat
import com.hsy.swu.R
import com.hsy.swu.hsyutils.MActivityUtil
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.util.TextInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.reflect.Method

/**
 * 判断移动数据是否打开
 *
 * @return `true`: 是<br></br>`false`: 否
 */
private fun getDataEnabled(context: Context): Boolean {
    try {
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val getMobileDataEnabledMethod: Method? = tm.javaClass.getDeclaredMethod("getDataEnabled")
        if (getMobileDataEnabledMethod != null) {
            return getMobileDataEnabledMethod.invoke(tm) as Boolean
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return false
}

/**
 * 判断wifi数据是否可用
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 *
 * @return `true`: 是<br></br>`false`: 否
 */
private fun isWifiAvailable(context: Context): Boolean {
    return getWifiEnabled(context) && isWiFiActive(context)
}

/**
 * 判断wifi是否打开
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
 *
 * @return `true`: 是<br></br>`false`: 否
 */
private fun getWifiEnabled(context: Context): Boolean {
    val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    return wifiManager.isWifiEnabled
}

/**
 * 判断WIFI是否链接
 *
 * @param inContext
 * @return
 */
private fun isWiFiActive(inContext: Context): Boolean {
    val mWifiManager = inContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    val wifiInfo: WifiInfo = mWifiManager.connectionInfo
    val ipAddress: Int = wifiInfo.ipAddress
    return mWifiManager.isWifiEnabled && ipAddress != 0
}

fun Context.forceSendRequestByMobileData(onContinueCallback: () -> Unit) {
    // 判断移动网络是否已连接
    if (getDataEnabled(this)) {
        // 判断WiFi是否链接
        if (isWifiAvailable(this)) {
            val connectivityManager =
                getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val builder = NetworkRequest.Builder()
            builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            // 强制使用蜂窝数据网络-移动数据
            builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            val request = builder.build()
            connectivityManager.requestNetwork(
                request,
                object : ConnectivityManager.NetworkCallback() {
                    override fun onAvailable(network: Network) {
                        super.onAvailable(network)
                        connectivityManager.bindProcessToNetwork(network)
                        CoroutineScope(Dispatchers.Main).launch {
                            onContinueCallback()
                        }
                    }
                })
        } else {
            onContinueCallback()
        }
    } else {
        MessageDialog.build()
            .setTitle("检测到未开启移动数据，使用流量比直接使用 wifi 刷新的速度快很多，请下滑状态栏手动开启。")
            .setCancelButton("直接使用 wifi\n（可能更新失败）") { _, _ ->
                onContinueCallback()
                return@setCancelButton false
            }
            .setCancelTextInfo(TextInfo().apply {
                fontColor = ContextCompat.getColor(MessageDialog.getContext(), R.color.lightGray)
            })
            .setOkButton("现在开了\n继续") { _, _ ->
                return@setOkButton if (getDataEnabled(this)) {
                    forceSendRequestByMobileData(onContinueCallback)
                    false
                } else {
                    MActivityUtil.showToast("没开")
                    true
                }
            }
            .setCancelable(false)
            .show()
    }
}

fun Context.releaseNetWorkBind() {
    (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
        .bindProcessToNetwork(null)
}

fun Context.openMobileNetworkSettings() {
    val intent = Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)
    // 或者使用 Intent(Settings.ACTION_SETTINGS) 打开整个设置页面
    startActivity(intent)
}